package cn.edu.njust.limiter;

import java.util.concurrent.*;

public class CounterRateLimiter implements RateLimiter {

    private Semaphore semaphore;

    private int ops;

    private ScheduledExecutorService scheduler;

    public CounterRateLimiter(int ops) {
        this.ops = ops;
        this.semaphore = new Semaphore(0);
        this.scheduler = Executors.newSingleThreadScheduledExecutor(new ThreadFactory() {
            @Override
            public Thread newThread(Runnable r) {
                return new Thread(r, "CounterRateLimiterThread");
            }
        });
        // 每隔一秒往桶里添加QPS个令牌
        this.scheduler.scheduleAtFixedRate(() -> {
            semaphore.release(ops - semaphore.availablePermits());
        }, 0, 1, TimeUnit.SECONDS);
    }

    @Override
    public void aquire() throws InterruptedException {
        semaphore.acquire();
    }
}
